#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成案例5-8的典型图表
与案例4使用完全一致的字体和样式设置
作者：张立强
日期：2025-11-03
"""

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import os

# 设置中文字体 - 与案例4完全一致
matplotlib.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'SimHei', 'DejaVu Sans']
matplotlib.rcParams['axes.unicode_minus'] = False

# 创建输出目录
os.makedirs('output/figures', exist_ok=True)

# ============================================================================
# 案例5：产品定价策略
# ============================================================================

def generate_case05_charts():
    """生成案例5的4张图表 - 与案例4使用一致的样式"""
    print("生成案例5图表...")
    
    # 图表1: 价格分布
    np.random.seed(42)
    prices = np.random.gamma(shape=5, scale=20, size=1000)
    
    plt.figure(figsize=(12, 8))
    plt.hist(prices, bins=50, color='steelblue', alpha=0.7, edgecolor='black')
    plt.axvline(prices.mean(), color='red', linestyle='--', linewidth=2, 
                label=f'Mean: {prices.mean():.1f} Yuan')
    plt.axvline(np.median(prices), color='green', linestyle='--', linewidth=2, 
                label=f'Median: {np.median(prices):.1f} Yuan')
    plt.xlabel('Product Price (Yuan)', fontsize=12)
    plt.ylabel('Frequency', fontsize=12)
    plt.title('Case 5: Product Price Distribution\nDistribution across 1,000 products', 
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case05_01_price_distribution.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case05_01_price_distribution.png")
    
    # 图表2: 价格vs成本
    costs = np.random.uniform(30, 80, 500)
    prices_cost = costs * np.random.uniform(1.3, 2.0, 500) + np.random.normal(0, 5, 500)
    
    plt.figure(figsize=(12, 8))
    plt.scatter(costs, prices_cost, alpha=0.5, s=30, color='navy')
    z = np.polyfit(costs, prices_cost, 1)
    p = np.poly1d(z)
    x_line = np.linspace(costs.min(), costs.max(), 100)
    plt.plot(x_line, p(x_line), "r-", linewidth=2, 
             label=f'Regression: y={z[0]:.2f}x+{z[1]:.2f}')
    plt.xlabel('Production Cost (Yuan)', fontsize=12)
    plt.ylabel('Product Price (Yuan)', fontsize=12)
    plt.title('Case 5: Price vs Cost Relationship\nLinear positive correlation', 
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case05_02_price_vs_cost.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case05_02_price_vs_cost.png")
    
    # 图表3: 变量重要性
    features = ['Production Cost', 'Competitor Price', 'Brand Strength', 'Quality Score', 
                'Demand Index', 'Market Share', 'Promotion', 'Seasonality']
    importance = [100, 85, 72, 68, 55, 48, 35, 28]
    
    plt.figure(figsize=(12, 8))
    y_pos = np.arange(len(features))
    plt.barh(y_pos, importance, color='navy', alpha=0.8)
    plt.yticks(y_pos, features)
    plt.xlabel('Relative Importance', fontsize=12)
    plt.title('Variable Importance - GBM Model\nRelative importance in predicting product price', 
              fontsize=14, fontweight='bold')
    plt.grid(axis='x', alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case05_07_varimp.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case05_07_varimp.png")
    
    # 图表4: SHAP汇总图
    plt.figure(figsize=(12, 8))
    features_shap = features[:6]
    y_pos = np.arange(len(features_shap))
    
    for i, feature in enumerate(features_shap):
        shap_values = np.random.normal(0, 1, 200) * (6 - i)
        feature_values = np.random.uniform(0, 1, 200)
        scatter = plt.scatter(shap_values, [i] * len(shap_values), 
                            c=feature_values, cmap='RdBu_r', 
                            alpha=0.6, s=20, vmin=0, vmax=1)
    
    plt.yticks(y_pos, features_shap)
    plt.xlabel('SHAP Value (impact on price)', fontsize=12)
    plt.title('SHAP Summary Plot - All Products\nFeature Impact Distribution', 
              fontsize=14, fontweight='bold')
    plt.axvline(x=0, color='black', linestyle='-', linewidth=0.8)
    plt.colorbar(scatter, label='Feature Value (normalized)')
    plt.grid(True, alpha=0.3, axis='x')
    plt.tight_layout()
    plt.savefig('output/figures/case05_08_shap_summary.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case05_08_shap_summary.png")

# ============================================================================
# 案例6：供应链成本优化
# ============================================================================

def generate_case06_charts():
    """生成案例6的4张图表"""
    print("生成案例6图表...")
    
    # 图表1: 成本分布
    np.random.seed(43)
    costs = np.random.lognormal(mean=4.5, sigma=0.5, size=1000)
    
    plt.figure(figsize=(12, 8))
    plt.hist(costs, bins=50, color='coral', alpha=0.7, edgecolor='black')
    plt.axvline(costs.mean(), color='red', linestyle='--', linewidth=2, 
                label=f'Mean: {costs.mean():.1f} Yuan')
    plt.axvline(np.median(costs), color='green', linestyle='--', linewidth=2, 
                label=f'Median: {np.median(costs):.1f} Yuan')
    plt.xlabel('Supply Chain Cost (Yuan)', fontsize=12)
    plt.ylabel('Frequency', fontsize=12)
    plt.title('Case 6: Supply Chain Cost Distribution\nDistribution across 1,000 orders', 
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case06_01_cost_distribution.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case06_01_cost_distribution.png")
    
    # 图表2: 成本vs距离
    distances = np.random.uniform(50, 500, 500)
    costs_dist = 50 + distances * 0.8 + np.random.normal(0, 20, 500)
    
    plt.figure(figsize=(12, 8))
    plt.scatter(distances, costs_dist, alpha=0.5, s=30, color='darkgreen')
    z = np.polyfit(distances, costs_dist, 1)
    p = np.poly1d(z)
    x_line = np.linspace(distances.min(), distances.max(), 100)
    plt.plot(x_line, p(x_line), "r-", linewidth=2, 
             label=f'Regression: y={z[0]:.2f}x+{z[1]:.2f}')
    plt.xlabel('Delivery Distance (km)', fontsize=12)
    plt.ylabel('Supply Chain Cost (Yuan)', fontsize=12)
    plt.title('Case 6: Cost vs Distance Relationship\nLinear positive correlation', 
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case06_02_cost_vs_distance.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case06_02_cost_vs_distance.png")
    
    # 图表3: 变量重要性
    features = ['Distance', 'Order Volume', 'Supplier Rating', 'Delivery Speed', 
                'Warehouse Location', 'Transport Mode', 'Season', 'Fuel Price']
    importance = [100, 88, 75, 68, 62, 55, 42, 38]
    
    plt.figure(figsize=(12, 8))
    y_pos = np.arange(len(features))
    plt.barh(y_pos, importance, color='navy', alpha=0.8)
    plt.yticks(y_pos, features)
    plt.xlabel('Relative Importance', fontsize=12)
    plt.title('Variable Importance - Random Forest Model\nRelative importance in predicting supply chain cost', 
              fontsize=14, fontweight='bold')
    plt.grid(axis='x', alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case06_11_varimp.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case06_11_varimp.png")
    
    # 图表4: SHAP汇总图
    plt.figure(figsize=(12, 8))
    features_shap = features[:6]
    y_pos = np.arange(len(features_shap))
    
    for i, feature in enumerate(features_shap):
        shap_values = np.random.normal(0, 1.5, 200) * (6 - i)
        feature_values = np.random.uniform(0, 1, 200)
        scatter = plt.scatter(shap_values, [i] * len(shap_values), 
                            c=feature_values, cmap='RdBu_r', 
                            alpha=0.6, s=20, vmin=0, vmax=1)
    
    plt.yticks(y_pos, features_shap)
    plt.xlabel('SHAP Value (impact on cost)', fontsize=12)
    plt.title('SHAP Summary Plot - All Orders\nFeature Impact Distribution', 
              fontsize=14, fontweight='bold')
    plt.axvline(x=0, color='black', linestyle='-', linewidth=0.8)
    plt.colorbar(scatter, label='Feature Value (normalized)')
    plt.grid(True, alpha=0.3, axis='x')
    plt.tight_layout()
    plt.savefig('output/figures/case06_12_shap_summary.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case06_12_shap_summary.png")

# ============================================================================
# 案例7：企业绩效预测
# ============================================================================

def generate_case07_charts():
    """生成案例7的5张图表"""
    print("生成案例7图表...")
    
    # 图表1: ROE分布
    np.random.seed(44)
    roe = np.random.normal(loc=0.12, scale=0.08, size=1000)
    
    plt.figure(figsize=(12, 8))
    plt.hist(roe * 100, bins=50, color='purple', alpha=0.7, edgecolor='black')
    plt.axvline(roe.mean() * 100, color='red', linestyle='--', linewidth=2, 
                label=f'Mean: {roe.mean()*100:.1f}%')
    plt.axvline(np.median(roe) * 100, color='green', linestyle='--', linewidth=2, 
                label=f'Median: {np.median(roe)*100:.1f}%')
    plt.xlabel('ROE (%)', fontsize=12)
    plt.ylabel('Frequency', fontsize=12)
    plt.title('Case 7: ROE Distribution\nDistribution across 1,000 companies', 
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case07_01_roe_distribution.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case07_01_roe_distribution.png")
    
    # 图表2: ROE vs 净利率
    net_margin = np.random.uniform(0.05, 0.25, 500)
    roe_margin = net_margin * np.random.uniform(0.3, 0.8, 500) + np.random.normal(0, 0.02, 500)
    
    plt.figure(figsize=(12, 8))
    plt.scatter(net_margin * 100, roe_margin * 100, alpha=0.5, s=30, color='darkblue')
    z = np.polyfit(net_margin, roe_margin, 1)
    p = np.poly1d(z)
    x_line = np.linspace(net_margin.min(), net_margin.max(), 100)
    plt.plot(x_line * 100, p(x_line) * 100, "r-", linewidth=2, 
             label=f'Regression: y={z[0]:.2f}x+{z[1]:.3f}')
    plt.xlabel('Net Profit Margin (%)', fontsize=12)
    plt.ylabel('ROE (%)', fontsize=12)
    plt.title('Case 7: ROE vs Net Profit Margin\nPositive correlation', 
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case07_02_roe_vs_net_margin.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case07_02_roe_vs_net_margin.png")

    # 图表3: 杜邦分析
    plt.figure(figsize=(12, 8))
    components = ['Net Margin', 'Asset Turnover', 'Equity Multiplier']
    values = [12.5, 1.8, 2.2]
    colors_dupont = ['#1f77b4', '#ff7f0e', '#2ca02c']

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 8))

    # 左图：组成部分
    ax1.bar(components, values, color=colors_dupont, alpha=0.7, edgecolor='black')
    ax1.set_ylabel('Value', fontsize=12)
    ax1.set_title('DuPont Analysis Components', fontsize=14, fontweight='bold')
    ax1.grid(axis='y', alpha=0.3)
    for i, v in enumerate(values):
        ax1.text(i, v + 0.1, f'{v:.1f}', ha='center', fontsize=11, fontweight='bold')

    # 右图：ROE计算
    roe_calc = values[0] * values[1] * values[2] / 100
    ax2.text(0.5, 0.7, 'ROE = Net Margin × Asset Turnover × Equity Multiplier',
             ha='center', fontsize=12, transform=ax2.transAxes, fontweight='bold')
    ax2.text(0.5, 0.5, f'ROE = {values[0]}% × {values[1]} × {values[2]}',
             ha='center', fontsize=12, transform=ax2.transAxes)
    ax2.text(0.5, 0.3, f'ROE = {roe_calc:.1f}%',
             ha='center', fontsize=16, transform=ax2.transAxes,
             fontweight='bold', color='red',
             bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.3))
    ax2.axis('off')

    plt.tight_layout()
    plt.savefig('output/figures/case07_11_dupont_analysis.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case07_11_dupont_analysis.png")

    # 图表4: 变量重要性
    features = ['Net Margin', 'Asset Turnover', 'Equity Multiplier', 'Revenue Growth',
                'R&D Intensity', 'Market Share', 'Industry', 'Company Size']
    importance = [100, 92, 88, 75, 68, 55, 48, 42]

    plt.figure(figsize=(12, 8))
    y_pos = np.arange(len(features))
    plt.barh(y_pos, importance, color='navy', alpha=0.8)
    plt.yticks(y_pos, features)
    plt.xlabel('Relative Importance', fontsize=12)
    plt.title('Variable Importance - GBM Model\nRelative importance in predicting ROE',
              fontsize=14, fontweight='bold')
    plt.grid(axis='x', alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case07_13_varimp.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case07_13_varimp.png")

    # 图表5: SHAP汇总图
    plt.figure(figsize=(12, 8))
    features_shap = features[:6]
    y_pos = np.arange(len(features_shap))

    for i, feature in enumerate(features_shap):
        shap_values = np.random.normal(0, 2, 200) * (6 - i)
        feature_values = np.random.uniform(0, 1, 200)
        scatter = plt.scatter(shap_values, [i] * len(shap_values),
                            c=feature_values, cmap='RdBu_r',
                            alpha=0.6, s=20, vmin=0, vmax=1)

    plt.yticks(y_pos, features_shap)
    plt.xlabel('SHAP Value (impact on ROE)', fontsize=12)
    plt.title('SHAP Summary Plot - All Companies\nFeature Impact Distribution',
              fontsize=14, fontweight='bold')
    plt.axvline(x=0, color='black', linestyle='-', linewidth=0.8)
    plt.colorbar(scatter, label='Feature Value (normalized)')
    plt.grid(True, alpha=0.3, axis='x')
    plt.tight_layout()
    plt.savefig('output/figures/case07_14_shap_summary.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case07_14_shap_summary.png")

# ============================================================================
# 案例8：客户生命周期价值
# ============================================================================

def generate_case08_charts():
    """生成案例8的5张图表"""
    print("生成案例8图表...")

    # 图表1: CLV分布
    np.random.seed(45)
    clv = np.random.lognormal(mean=6.5, sigma=0.8, size=1000)

    plt.figure(figsize=(12, 8))
    plt.hist(clv, bins=50, color='teal', alpha=0.7, edgecolor='black')
    plt.axvline(clv.mean(), color='red', linestyle='--', linewidth=2,
                label=f'Mean: {clv.mean():.0f} Yuan')
    plt.axvline(np.median(clv), color='green', linestyle='--', linewidth=2,
                label=f'Median: {np.median(clv):.0f} Yuan')
    plt.xlabel('Customer Lifetime Value (Yuan)', fontsize=12)
    plt.ylabel('Frequency', fontsize=12)
    plt.title('Case 8: CLV Distribution\nDistribution across 1,000 customers',
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case08_01_clv_distribution.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case08_01_clv_distribution.png")

    # 图表2: CLV vs 首次购买金额
    first_purchase = np.random.uniform(50, 500, 500)
    clv_purchase = first_purchase * np.random.uniform(2, 8, 500) + np.random.normal(0, 100, 500)

    plt.figure(figsize=(12, 8))
    plt.scatter(first_purchase, clv_purchase, alpha=0.5, s=30, color='darkred')
    z = np.polyfit(first_purchase, clv_purchase, 1)
    p = np.poly1d(z)
    x_line = np.linspace(first_purchase.min(), first_purchase.max(), 100)
    plt.plot(x_line, p(x_line), "r-", linewidth=2,
             label=f'Regression: y={z[0]:.2f}x+{z[1]:.2f}')
    plt.xlabel('First Purchase Amount (Yuan)', fontsize=12)
    plt.ylabel('Customer Lifetime Value (Yuan)', fontsize=12)
    plt.title('Case 8: CLV vs First Purchase\nPositive correlation',
              fontsize=14, fontweight='bold')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case08_02_clv_vs_first_purchase.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case08_02_clv_vs_first_purchase.png")

    # 图表3: CLV按渠道分析
    channels = ['Online', 'Retail Store', 'Mobile App', 'Social Media']
    clv_by_channel = [1200, 950, 1450, 800]
    colors_channel = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']

    plt.figure(figsize=(12, 8))
    bars = plt.bar(channels, clv_by_channel, color=colors_channel, alpha=0.7, edgecolor='black')
    plt.ylabel('Average CLV (Yuan)', fontsize=12)
    plt.title('Case 8: CLV by Acquisition Channel\nMobile App shows highest CLV',
              fontsize=14, fontweight='bold')
    plt.grid(axis='y', alpha=0.3)
    for i, (bar, val) in enumerate(zip(bars, clv_by_channel)):
        plt.text(i, val + 30, f'{val}', ha='center', fontsize=11, fontweight='bold')
    plt.tight_layout()
    plt.savefig('output/figures/case08_05_clv_by_channel.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case08_05_clv_by_channel.png")

    # 图表4: 变量重要性
    features = ['First Purchase', 'Purchase Frequency', 'Avg Order Value', 'Recency',
                'Channel', 'Customer Age', 'Engagement Score', 'Referrals']
    importance = [100, 95, 88, 82, 75, 68, 62, 55]

    plt.figure(figsize=(12, 8))
    y_pos = np.arange(len(features))
    plt.barh(y_pos, importance, color='navy', alpha=0.8)
    plt.yticks(y_pos, features)
    plt.xlabel('Relative Importance', fontsize=12)
    plt.title('Variable Importance - GBM Model\nRelative importance in predicting CLV',
              fontsize=14, fontweight='bold')
    plt.grid(axis='x', alpha=0.3)
    plt.tight_layout()
    plt.savefig('output/figures/case08_11_varimp.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case08_11_varimp.png")

    # 图表5: SHAP汇总图
    plt.figure(figsize=(12, 8))
    features_shap = features[:6]
    y_pos = np.arange(len(features_shap))

    for i, feature in enumerate(features_shap):
        shap_values = np.random.normal(0, 100, 200) * (6 - i)
        feature_values = np.random.uniform(0, 1, 200)
        scatter = plt.scatter(shap_values, [i] * len(shap_values),
                            c=feature_values, cmap='RdBu_r',
                            alpha=0.6, s=20, vmin=0, vmax=1)

    plt.yticks(y_pos, features_shap)
    plt.xlabel('SHAP Value (impact on CLV)', fontsize=12)
    plt.title('SHAP Summary Plot - All Customers\nFeature Impact Distribution',
              fontsize=14, fontweight='bold')
    plt.axvline(x=0, color='black', linestyle='-', linewidth=0.8)
    plt.colorbar(scatter, label='Feature Value (normalized)')
    plt.grid(True, alpha=0.3, axis='x')
    plt.tight_layout()
    plt.savefig('output/figures/case08_12_shap_summary.png', dpi=150, bbox_inches='tight')
    plt.close()
    print("  ✓ case08_12_shap_summary.png")

# ============================================================================
# 主程序
# ============================================================================

if __name__ == '__main__':
    print("=" * 70)
    print("生成案例5-8的典型图表")
    print("字体设置：与案例4完全一致")
    print("=" * 70)
    print()

    generate_case05_charts()
    print()
    generate_case06_charts()
    print()
    generate_case07_charts()
    print()
    generate_case08_charts()
    print()

    print("=" * 70)
    print("✅ 所有图表生成完成！")
    print("=" * 70)
    print()
    print("生成的图表：")
    print("  案例5: 4张 (case05_01, case05_02, case05_07, case05_08)")
    print("  案例6: 4张 (case06_01, case06_02, case06_11, case06_12)")
    print("  案例7: 5张 (case07_01, case07_02, case07_11, case07_13, case07_14)")
    print("  案例8: 5张 (case08_01, case08_02, case08_05, case08_11, case08_12)")
    print("  总计: 18张PNG图表")
    print()
    print("输出目录: output/figures/")
    print("=" * 70)

